package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.PassengerApi;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.ActivityReturnEvent;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.ShareRecord;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.ActivityTarget;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.ActivityRecord;
import com.ybkj.daijia.server.sales.ActivityVo;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ShareRecordService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ActivityCheckEventListener implements ApplicationListener<ActivityCheckEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ActivityCheckEventListener.class);

    @Autowired
    private OrderService orderService;

    @Autowired
    private ErrandService errandService;

    @Autowired
    private ZhuancheService zhuancheService;

    @Autowired
    private FreightService freightService;

    @Autowired
    private ShareRecordService shareRecordService;

    @Autowired
    private CouponRuleService couponRuleService;

    @Autowired
    private SalesApi salesApi;

    @Autowired
    private PassengerApi passengerApi;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private ZhuanxianService zhuanxianService;


    @Override
    @Async
    public void onApplicationEvent(ActivityCheckEvent event) {
        logger.debug("activity check event:{}", "");

        ReactorVo vo = (ReactorVo) event.getSource();
        Long passengerId = vo.getPassenger().getId();
        //获取优惠活动  activityEvent='newRegister'
        ActivityEvent activityEvent = vo.getActivityEvent();
        System.out.println("before ServletException");
        try {
            //根据id获取用户
            Passenger passenger = passengerApi.findOnePassenger(passengerId, settingUtils.get())
                .getResult();
            System.out.println("after ServletException");
            Enterprise enterprise = null;

            if (null != passenger && passenger.getType().equals(1)) {
                enterprise = passengerApi
                    .findOneEnterprise(passenger.getEnterprise_id(), settingUtils.get())
                    .getResult();
            }

            if ((null != passenger && passenger.getType().equals(0)) || (null != passenger
                && passenger.getType().equals(1) && null != enterprise)) {

                Result<Activity> activityResult = salesApi.findValidByEvent(activityEvent);
                List<Activity> activities = activityResult.getData();
                if (!CollectionUtils.isEmpty(activities)) {
                    for (Activity activity : activities) {
                        //判断活动的公司id和新建用户所属公司id是否相同
                        if (activity.getCompanyIds()
                            .contains("," + String.valueOf(passenger.getCompanyId()) + ",")) {
                            //判断活动类型是不是新注册用户活动
                            if (activity.getActivityEvent().equals(ActivityEvent.newRegister)) {
                                //如果活动目标为全部会员 或者 (活动目标为个人并且新建用户类型为个人) 或者 (活动目标为企业会员并且新建用户类型为企业用户)
                                if ((activity.getActivityTarget().equals(ActivityTarget.all)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.passenger)
                                        && passenger.getType().equals(0)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.enterprise)
                                        && passenger.getType().equals(1))) {
                                    boolean gradeOk = false;
                                    //如果新建用户是个人用户
                                    if (passenger.getType().equals(0)) {
                                        if (null == passenger.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(passenger.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    }
                                    //如果新建用户是企业用户
                                    else if (passenger.getType().equals(1)) {
                                        if (null == enterprise.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(enterprise.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    }

                                    if (gradeOk) {
                                        boolean channelOk = false;
                                        if (activity.getPassengerFromSource()
                                            .contains(passenger.getChannel_name())) {
                                            channelOk = true;
                                        }

                                        if (channelOk) {
                                            startActivity(activity, passenger, enterprise);
                                        }

                                    }
                                }
                            }
                            //充值满？元活动
                            else if (activity.getActivityEvent()
                                .equals(ActivityEvent.recharging)) {//充值满
                                if ((activity.getActivityTarget().equals(ActivityTarget.all)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.passenger)
                                        && passenger.getType().equals(0)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.enterprise)
                                        && passenger.getType().equals(1))) {
                                    boolean gradeOk = false;
                                    if (passenger.getType().equals(0)) {
                                        if (null == passenger.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(passenger.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    } else if (passenger.getType().equals(1)) {
                                        if (null == enterprise.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(enterprise.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    }

                                    if (gradeOk) {
                                        boolean channelOk = false;
                                        if (activity.getPassengerFromSource()
                                            .contains(passenger.getChannel_name())) {
                                            channelOk = true;
                                        }

                                        if (channelOk) {
                                            if (vo.getMoney().doubleValue() >= activity
                                                .getRechargingMoney().doubleValue()) {
                                                startActivity(activity, passenger, enterprise);
                                            }
                                        }

                                    }
                                }
                            }
                            //分享成功活动
                            else if (activity.getActivityEvent()
                                .equals(ActivityEvent.shareSuccess)) {//分享

                                ShareRecord shareRecord = vo.getShareRecord();
                                shareRecord.setActivityId(activity.getId());
                                shareRecordService.insertRecord(shareRecord);

                                boolean sharePlatformOk = false;
                                if (activity.getSharePlatforms().contains(
                                    "," + shareRecord.getSharePlatform().toString() + ",")) {
                                    sharePlatformOk = true;
                                }
                                if (sharePlatformOk) {

                                    Integer shareTimes = activity.getShareTimes();//满足的分享次数
                                    Integer restriction = activity.getRestriction();//限制领取次数

                                    //已经分享的次数
                                    Date startDate = new Date(activity.getStart());
                                    Date endDate = null;
                                    if (null != activity.getEnd()) {
                                        endDate = new Date(activity.getEnd());
                                    }
                                    Long recordTimes = shareRecordService
                                        .countByMemberAndActivity(passenger.getId(),
                                            activity.getId(), startDate, endDate);
                                    if (recordTimes != 0 && recordTimes % shareTimes == 0) {
                                        if (restriction == 0
                                            || (recordTimes / shareTimes) <= restriction) {
                                            startActivity(activity, passenger, enterprise);
                                        }
                                    }

                                }
                            }
                            //邀请成功活动
                            else if (activity.getActivityEvent()
                                .equals(ActivityEvent.invite)) {//邀请新客户

                                startActivity(activity, passenger, enterprise);

                            } else if (activity.getActivityEvent()
                                .equals(ActivityEvent.orderCompleteTimes)) {//完成订单
                                if ((activity.getActivityTarget().equals(ActivityTarget.all)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.passenger)
                                        && passenger.getType().equals(0)) ||
                                    (activity.getActivityTarget().equals(ActivityTarget.enterprise)
                                        && passenger.getType().equals(1))) {
                                    boolean gradeOk = false;
                                    if (passenger.getType().equals(0)) {
                                        if (null == passenger.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(passenger.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    } else if (passenger.getType().equals(1)) {
                                        if (null == enterprise.getGrade_id() || StringUtils
                                            .isBlank(activity.getGradeIds()) || activity
                                            .getGradeIds().contains(
                                                "," + String.valueOf(enterprise.getGrade_id())
                                                    + ",")) {
                                            gradeOk = true;
                                        }
                                    }

                                    if (gradeOk) {
                                        boolean orderFromSouceOK = false;
                                        if (activity.getOrderFromSource()
                                            .contains(vo.getOrderChannelName())) {
                                            orderFromSouceOK = true;
                                        }

                                        if (orderFromSouceOK) {
                                            if (activity.getOrderType().equals(vo.getOrderType())) {
                                                Integer completeTimes = activity
                                                    .getCompleteTimes();//满足的完成次数
                                                Integer restriction = activity
                                                    .getRestriction();//限制领取次数

                                                Long completeTimesNow = 0L;//已经完成的次数

                                                Long activityTimes = salesApi
                                                    .countActivityRecord(passengerId,
                                                        activity.getId());//实际参与了多少次

                                                Date startDate = new Date(activity.getStart());
                                                Date endDate = null;
                                                if (null != activity.getEnd()) {
                                                    endDate = new Date(activity.getEnd());
                                                }

                                                String[] orderFromSources = activity
                                                    .getOrderFromSource().split(",");

                                                if (activity.getOrderType()
                                                    .equals(OrderType.daijia)) {
                                                    completeTimesNow = orderService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passengerId, orderFromSources,
                                                            startDate, endDate);
                                                } else if (activity.getOrderType()
                                                    .equals(OrderType.zhuanche)) {
                                                    completeTimesNow = zhuancheService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passengerId,
                                                            activity.getOrderFromSource(),
                                                            startDate, endDate);
                                                } else if (activity.getOrderType()
                                                    .equals(OrderType.errand)) {
                                                    completeTimesNow = errandService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passengerId,
                                                            activity.getOrderFromSource(),
                                                            startDate, endDate);
                                                } else if (activity.getOrderType()
                                                    .equals(OrderType.freight)) {
                                                    completeTimesNow = freightService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passengerId,
                                                            activity.getOrderFromSource(),
                                                            startDate, endDate);
                                                } else if (activity.getOrderType()
                                                    .equals(OrderType.zhuanxian)) {
                                                    completeTimesNow = zhuanxianService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passenger.getId(),
                                                            activity.getOrderFromSource(),
                                                            startDate, endDate);
                                                } else if (activity.getOrderType()
                                                    .equals(OrderType.errand)) {
                                                    completeTimesNow = errandService
                                                        .countFinishedByPassengerAndFinishTime(
                                                            passenger.getId(),
                                                            activity.getOrderFromSource(),
                                                            startDate, endDate);
                                                }

                                                if (completeTimesNow != 0
                                                    && completeTimesNow % completeTimes == 0) {
                                                    if (restriction == 0
                                                        || activityTimes < restriction) {
                                                        startActivity(activity, passenger,
                                                            enterprise);
                                                    }
                                                }

                                            }

                                        }

                                    }

                                }
                            }
                        }
                    }
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startActivity(Activity activity, Passenger passenger, Enterprise enterprise) {

        Result<ActivityVo> result = salesApi.startActivity(activity, passenger, enterprise);

        if (result.isSuccess()) {
            ActivityVo activityVo = result.getResult();
            ActivityRecord activityRecord = activityVo.getActivityRecord();
            if (null != activityRecord.getId()) {
                if (StringUtils.isNotBlank(activity.getMessageType())) {
                    ActivityReturnEvent activityReturnEvent = new ActivityReturnEvent(activity,
                        activityVo, activityRecord.getMemo(), passenger);
                    applicationEventMulticaster.multicastEvent(activityReturnEvent);
                }
            }
        }

    }


}
